package com.suriya.thirukural;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.admob.android.ads.AdManager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class KuralView extends Activity
{
    private ThirukuralContext _context;
    private AssetManager      assetManager;
    private int               orientation;
    private int[]             section;
    private int               depth;
    private int               kuralNum;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        _context = (ThirukuralContext) getApplication();
        _context.init();

        AdManager.setTestDevices(new String[] { AdManager.TEST_EMULATOR });
        getWindow().setFormat(PixelFormat.RGBA_8888);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);

        assetManager = getAssets();
        Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        orientation = display.getOrientation();

        Intent intent = getIntent();

        section = intent.getIntArrayExtra("section");
        if(section == null) section = new int[0];
        depth = intent.getIntExtra("depth", 0);
        kuralNum = intent.getIntExtra("kuralNum", 1);

        Log.d("Suriya", "Depth:" + depth + " KuralNum:" + kuralNum);

        for(int curr : section)
        {
            Log.d("Suriya", "KuralView:" + curr);
        }
        setContentView(R.layout.kural_view);

        LinearLayout layout = (LinearLayout) findViewById(R.id.screenview);
        layout.setBackgroundDrawable(_context.getBackgroundImage());

        String sectionStr = "sections";
        String expName = "section_";

        for(int currSection : section)
        {
            sectionStr += ("/" + currSection);
            expName += ("" + currSection + "_");
        }

        {
            String imgPath = "sections/";
            String filenamePart = "section";

            for(int idx = 1; idx <= depth && idx <= 3; idx++)
            {
                filenamePart += "_" + section[idx - 1];
                ImageView img = null;
                if(idx == 1)
                {
                    img = (ImageView) findViewById(R.id.imgsec1);
                    img.setOnClickListener(sectionHeadClickListener);
                }
                else if(idx == 2)
                {
                    img = (ImageView) findViewById(R.id.imgsec2);
                    img.setOnClickListener(sectionHeadClickListener);
                }
                else if(idx == 3)
                {
                    img = (ImageView) findViewById(R.id.imgsec3);
                    img.setOnClickListener(sectionHeadClickListener);
                }

                Log.d("Suriya", "Loading image:" + imgPath + filenamePart + ".png");
                if(img != null)
                    img.setImageBitmap(MainActivity.getBitmap(assetManager, this, imgPath + filenamePart + ".png"));

                imgPath += "" + section[idx - 1] + "/";

            }
        }

        String expFile = sectionStr + "/ex_" + kuralNum;
        String trFile = sectionStr + "/tr_" + kuralNum;
        String kuralFile = sectionStr + "/kural.png";

        View view = findViewById(R.id.kural_holder);
        ImageView kural = (ImageView) findViewById(R.id.kural);
        TextView explaination = (TextView) findViewById(R.id.explaination);
        TextView trans1 = (TextView) findViewById(R.id.translation1);
        TextView trans2 = (TextView) findViewById(R.id.translation2);
        TextView sourceSite = (TextView) findViewById(R.id.source_site);

        sourceSite.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v)
            {
                Uri uri = Uri.parse( "http://www.muthu.org" );
                startActivity( new Intent( Intent.ACTION_VIEW, uri ) );
            }
        });

        LayoutParams param = view.getLayoutParams();

        if(orientation == 1)
        {
            param.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 80.0,
                                                           getResources().getDisplayMetrics());
        }
        else
        {
            param.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 50.0,
                                                           getResources().getDisplayMetrics());
        }
        view.setLayoutParams(param);

        {
            try
            {
                InputStream stream = assetManager.open(kuralFile);
                BufferedInputStream bis = new BufferedInputStream(stream);
                Bitmap kuralBm = BitmapFactory.decodeStream(bis);
                bis.close();
                stream.close();

                if(kuralBm != null)
                {
                    int position = kuralNum - 1;
                    Bitmap bm = Bitmap.createBitmap(kuralBm, 0, position * (kuralBm.getHeight() / 10),
                                                    kuralBm.getWidth(), kuralBm.getHeight() / 10);
                    kural.setImageBitmap(bm);
                }
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
        {
            try
            {
                InputStream stream = assetManager.open(expFile);
                BufferedInputStream bis = new BufferedInputStream(stream);
                byte inText[] = new byte[5000];
                int recvBytes = bis.read(inText);
                bis.close();
                stream.close();

                String inStr = new String(inText, 0, recvBytes - 1);
                explaination.setText(inStr);
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }

        {
            try
            {
                InputStream stream = assetManager.open(trFile);
                BufferedInputStream bis = new BufferedInputStream(stream);
                byte inText[] = new byte[5000];
                bis.read(inText);
                bis.close();
                stream.close();

                String inStr = new String(inText);
                String lines[] = inStr.split("\n");

                trans1.setText(lines[0]);
                trans2.setText(lines[1]);
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }

        AdManager.setTestDevices(new String[] { AdManager.TEST_EMULATOR });
    }

    public void onGotoMainMenu(View v)
    {
        Intent intent = new Intent(_context, MainActivity.class);
        startActivity(intent);
    }

    private OnClickListener sectionHeadClickListener = new OnClickListener() {

                                                         @Override
                                                         public void onClick(View v)
                                                         {
                                                             int newSections[] = {};

                                                             if(v == findViewById(R.id.imgsec1))
                                                             {
                                                                 newSections = new int[1];
                                                             }
                                                             else if(v == findViewById(R.id.imgsec2))
                                                             {
                                                                 newSections = new int[2];
                                                             }
                                                             else if(v == findViewById(R.id.imgsec3))
                                                             {
                                                                 newSections = new int[3];
                                                             }

                                                             if(depth == newSections.length) return;

                                                             for(int idx = 0; idx < newSections.length; idx++)
                                                             {
                                                                 newSections[idx] = section[idx];
                                                             }

                                                             Intent intent = new Intent(_context, MainActivity.class);
                                                             intent.putExtra("section", newSections);
                                                             intent.putExtra("depth", newSections.length);
                                                             startActivity(intent);
                                                         }
                                                     };
}
